<template>
  <div class="number-container">
      <div class="number-title">{{title}}</div>
      <div>
        <span :style="innerStyle">{{number}}</span>
        <span :style="unitStyle">{{unit}}</span>
      </div>
  </div>
</template>

<script>
export default {
    props:{
        title: String,
        fontSize: Number,
        fontColor: String,
        unit: String,
        data: Array,
        y: Array
    },
    data(){
        return {
            number: 0
        }
    },
    methods: {
        initData(){
            if(!this.data || !this.y || this.y.length === 0) {
                this.number = 0
                return
            }
            if(this.y.length > 1){
                this.$message.warning('数值图不能展示两个或以上指标数据，仅展示首位指标数据')
            }
            let data = this.data.find(d => d.name === this.y[0].field)?.data
            if(!data){
                this.number = 0
                return
            }

            switch(this.y[0].computeType){
                case 'sum':
                    this.number = data.reduce((prev,current)=>{
                        return prev + current
                    })
                    break
                case 'mean':
                    this.number = data.reduce((prev,current)=>{
                        return prev + current
                    }) / data.length
                    break
                case 'max':
                    this.number = Math.max(...data)
                    break
                case 'min':
                    this.number = Math.min(...data)
                    break
                case 'count':
                    this.number = data.length
                    break
            }
        }
    },
    computed:{
        innerStyle(){
            return {
                fontSize: `${this.fontSize}px`,
                color: this.fontColor
            }
        },
        unitStyle(){
            return {
                fontSize: `${(this.fontSize/2)}px`,
                color: this.fontColor
            }
        }
    },
    watch:{
        y:{
            deep:true,
            handler: function(){
                this.initData()
            }
        },
    },
    mounted(){
        this.initData()
    }
}
</script>

<style lang="less">
.number-container{
    width: 100%;
    height: 100%;
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    font-family: system-ui,-apple-system,BlinkMacSystemFont,segoe ui,Roboto,Helvetica,Arial,sans-serif,apple color emoji,segoe ui emoji,segoe ui symbol;
    
    .number-title{
        position: absolute;
        left: 5px;
        top: 5px;
        font-weight: 700;
        font-size: 16px;
        color: black;
    }

    span{
        font-weight: 500;
        font-size: 20px;
    }
}
</style>